import React, { useEffect, useState } from 'react';
import { useParams, Link, useNavigate } from 'react-router-dom';
import axios from 'axios';
import MainLayout from '../../components/MainLayout';
import { resourceService } from '../../services/categories';
import Toast from '../../components/Toast.js';
import PaginationComponent from '../network/NetworkHome/components/PaginationComponent.js';
import './ResourceDetail.css';

const API_BASE_URL = 'http://117.72.106.234:8080/api';

// 创建axios实例
const resourceApi = axios.create({
    baseURL: API_BASE_URL,
    headers: {
      'Content-Type': 'application/json',
    },
  });
  
  // 请求拦截器 - 添加token
  resourceApi.interceptors.request.use(
    (config) => {
      const token = localStorage.getItem('token');
      if (token) {
        config.headers.Authorization = `Bearer ${token}`;
      }
      return config;
    },
    (error) => {
      return Promise.reject(error);
    }
  );
  
const ResourceDetail = () => {
  const { resourceId } = useParams();
  const navigate = useNavigate();
  const [resource, setResource] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [isLiked, setIsLiked] = useState(false);
  const [showPurchaseModal, setShowPurchaseModal] = useState(false);
  const [purchaseError, setPurchaseError] = useState(null);
  const [purchaseLoading, setPurchaseLoading] = useState(false);
  const [selectedNetworkId, setSelectedNetworkId] = useState(null);
  const [currentUser, setCurrentUser] = useState(null);
  const [toast, setToast] = useState({ show: false, message: '' });
  
  // 评论相关状态
  const [comments, setComments] = useState([]);
  const [commentsLoading, setCommentsLoading] = useState(false);
  const [commentsError, setCommentsError] = useState(null);
  const [newComment, setNewComment] = useState('');
  const [commentImages, setCommentImages] = useState([]);
  const [submittingComment, setSubmittingComment] = useState(false);
  const [activeTab, setActiveTab] = useState('detail');
  const [commentPageNum, setCommentPageNum] = useState(1);
  const [commentPageSize, setCommentPageSize] = useState(20);
  const [commentTotal, setCommentTotal] = useState(0);
  const [commentOrderBy, setCommentOrderBy] = useState('createTime');
  const [editingCommentId, setEditingCommentId] = useState(null);
  const [editingContent, setEditingContent] = useState('');

  // 显示Toast消息
  const showToast = (message) => {
    setToast({ show: true, message });
  };

  // 关闭Toast
  const closeToast = () => {
    setToast({ show: false, message: '' });
  };

   // 获取当前用户信息
   const fetchCurrentUser = async () => {
    try {
      const token = localStorage.getItem('token');
      if (!token) return null;
      
      const response = await resourceApi.get('/user/profile');
      if (response.data.code === 200) {
        setCurrentUser(response.data.data);
        return response.data.data;
      }
    } catch (err) {
    }
    return null;
  };

  useEffect(() => {
    const initializeComponent = async () => {
      // 先获取用户信息
      await fetchCurrentUser();
      
      // 然后获取资源详情
      await fetchResourceDetail();
    };

    const fetchResourceDetail = async () => {
      try {
        setLoading(true);
        const response = await resourceService.getResourceDetail(resourceId);
        if (response.data.code === 200) {
          setResource(response.data.data);
          // Check if user has liked this resource
          checkIfLiked(response.data.data.resourceId);
        } else {
          setError('获取资源详情失败');
        }
          } catch (err) {
      setError('获取资源详情失败，请稍后再试');
      } finally {
        setLoading(false);
      }
    };

    // 检查用户是否已点赞资源 - 使用新的API
    const checkIfLiked = async (id) => {
      try {
        const token = localStorage.getItem('token');
        if (!token) return; 
        
        const response = await resourceApi.get('/likes/status', {
          params: {
            targetId: id,
            targetType: 'resource'
          }
        });
        
        if (response.data.code === 200) {
          setIsLiked(response.data.data.liked);
        }
          } catch (err) {
    }
    };

    if (resourceId) {
      initializeComponent();
    } else {
      setError('资源ID无效');
      setLoading(false);
    }
  }, [resourceId]);

// 修复 fetchComments 函数中的数据结构问题

const fetchComments = async (resetPage = false) => {
  try {
    setCommentsLoading(true);
    
    const pageNum = resetPage ? 1 : commentPageNum;
    const currentUserId = currentUser?.userId;
    
    const response = await resourceApi.get(`/comments/resource/${resourceId}`, {
      params: {
        pageNum: pageNum,
        pageSize: commentPageSize,
        orderBy: commentOrderBy,
        currentUserId: currentUserId
      }
    });
    
    if (response.data.code === 200) {
      const newComments = response.data.data.comments || [];
      
      if (resetPage) {
        setComments(newComments);
        setCommentPageNum(1);
      } else {
        setComments(newComments);
      }
      
      setCommentTotal(response.data.data.total || 0);
      setCommentsError(null);
    } else {
      setCommentsError('获取评论失败');
      setComments([]);
    }
  } catch (err) {
    setCommentsError('获取评论失败，请稍后再试');
    setComments([]);
  } finally {
    setCommentsLoading(false);
  }
};

  // 当切换到评论tab时加载评论
  useEffect(() => {
    if (activeTab === 'comments') {
      fetchComments();
    }
  }, [activeTab, commentPageNum, commentOrderBy]);

  // 当资源数据加载完成后，设置默认选中的网络
  useEffect(() => {
    if (resource?.availableNetworks && resource.availableNetworks.length > 0) {
      // 默认选中用户是成员的第一个网络，或者选中第一个网络
      const defaultNetwork = resource.availableNetworks.find(network => network.isMember) 
        || resource.availableNetworks[0];
      setSelectedNetworkId(defaultNetwork.networkId);
    }
  }, [resource]);

  // 处理点赞 - 使用新的API
  const handleLike = async () => {
    const token = localStorage.getItem('token');
    if (!token) {
      navigate('/login', { state: { from: `/resource/detail/${resourceId}` } });
      return;
    }

    try {
      const response = await resourceApi.post('/likes', {
        targetId: parseInt(resourceId),
        targetType: 'resource',
        isLike: !isLiked
      });

      if (response.data.code === 200) {
        if (response.data.data.ischange) {
          setIsLiked(response.data.data.liked);
          setResource(prev => ({
            ...prev,
            likesCount: response.data.data.liked ? prev.likesCount + 1 : prev.likesCount - 1
          }));
        }
      }
    } catch (err) {
    }
  };

  // 提交评论
  const handleSubmitComment = async () => {
    const token = localStorage.getItem('token');
    if (!token) {
      navigate('/login', { state: { from: `/resource/detail/${resourceId}` } });
      return;
    }

    if (!newComment.trim()) {
      showToast('请输入评论内容');
      return;
    }

    try {
      setSubmittingComment(true);
      
      const formData = new FormData();
      formData.append('resourceId', resourceId);
      formData.append('content', newComment);
      
      // 添加图片文件
      commentImages.forEach((image, index) => {
        formData.append('images', image);
      });

      const response = await axios.post(`${API_BASE_URL}/comments/create`, formData, {
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'multipart/form-data'
        }
      });

      if (response.data.code === 200) {
        setNewComment('');
        setCommentImages([]);
        // 重新加载评论
        setCommentPageNum(1);
        fetchComments();
        // 更新资源的评论数量
        setResource(prev => ({
          ...prev,
          commentCount: (prev.commentCount || 0) + 1
        }));
      } else {
        showToast(response.data.message || '评论提交失败');
      }
    } catch (err) {
      showToast('评论提交失败，请稍后再试');
    } finally {
      setSubmittingComment(false);
    }
  };

  // 删除评论
  const handleDeleteComment = async (commentId) => {
    if (!window.confirm('确定要删除这条评论吗？')) {
      return;
    }
  
    try {
      const token = localStorage.getItem('token');
      if (!token) {
        navigate('/login', { state: { from: `/resource/detail/${resourceId}` } });
        return;
      }
  
      const response = await resourceApi.delete(`/comments/${commentId}`, {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      });
  
      if (response.data.code === 200) {
        fetchComments();
        setResource(prev => ({
          ...prev,
          commentCount: Math.max((prev.commentCount || 0) - 1, 0)
        }));
        showToast('评论删除成功');
      } else {
        showToast(response.data.message || '删除评论失败');
      }
    } catch (err) {
      if (err.response && err.response.data && err.response.data.message) {
        showToast(err.response.data.message);
      } else {
        showToast('删除评论失败，请稍后再试');
      }
    }
  };

  // 编辑评论
  const handleEditComment = (commentId, content) => {
    setEditingCommentId(commentId);
    setEditingContent(content);
  };

  // 保存编辑
  const handleSaveEdit = async (commentId) => {
    if (!editingContent.trim()) {
      showToast('请输入评论内容');
      return;
    }

    try {
      const response = await resourceApi.put(`/comments/update/${commentId}`, {
        content: editingContent
      });

      if (response.data.code === 200) {
        setEditingCommentId(null);
        setEditingContent('');
        fetchComments();
      } else {
        showToast(response.data.message || '更新评论失败');
      }
    } catch (err) {
      showToast('更新评论失败，请稍后再试');
    }
  };

  // 取消编辑
  const handleCancelEdit = () => {
    setEditingCommentId(null);
    setEditingContent('');
  };

  // 处理评论图片选择
  const handleCommentImageChange = (e) => {
    const files = Array.from(e.target.files);
    setCommentImages(files);
  };

  // 点赞评论
  const handleLikeComment = async (commentId, isLiked) => {
    const token = localStorage.getItem('token');
    if (!token) {
      navigate('/login', { state: { from: `/resource/detail/${resourceId}` } });
      return;
    }

    try {
      const response = await resourceApi.post('/likes', {
        targetId: commentId,
        targetType: 'comment',
        isLike: !isLiked
      });

      if (response.data.code === 200 && response.data.data.ischange) {
        // 更新评论列表中的点赞状态
        setComments(prev => prev.map(comment => {
          if (comment.commentId === commentId) {
            return {
              ...comment,
              isLiked: response.data.data.liked,
              likesCount: response.data.data.liked ? 
                (comment.likesCount || comment.likeCount || 0) + 1 : 
                Math.max((comment.likesCount || comment.likeCount || 0) - 1, 0),
              likeCount: response.data.data.liked ? 
                (comment.likesCount || comment.likeCount || 0) + 1 : 
                Math.max((comment.likesCount || comment.likeCount || 0) - 1, 0)
            };
          }
          return comment;
        }));
      }
    } catch (err) {
    }
  };

  const handlePurchase = async () => {
    const token = localStorage.getItem('token');
    if (!token) {
      navigate('/login', { state: { from: `/resource/detail/${resourceId}` } });
      return;
    }

    // 显示购买确认弹窗
    setShowPurchaseModal(true);
  };

  const confirmPurchase = async () => {
    setPurchaseLoading(true);
    setPurchaseError(null);
    
    try {
      const token = localStorage.getItem('token');
      const response = await axios.post(
        `${API_BASE_URL}/resource/purchase/${resourceId}`,
        {},
        { headers: { Authorization: `Bearer ${token}` } }
      );

      if (response.data.code === 200) {
        // 更新资源状态为已购买
        setResource(prev => ({
          ...prev,
          isPurchased: true,
          availableNetworks: response.data.data.availableNetworks || []
        }));
        
        // 关闭弹窗
        setShowPurchaseModal(false);
        
        // 显示获取成功提示
        showToast(resource.isFree ? '资源获取成功！' : '资源购买成功！');
      } else {
        setPurchaseError(response.data.message || '购买失败，请稍后再试');
      }
    } catch (err) {
      if (err.response && err.response.data && err.response.data.message) {
        setPurchaseError(err.response.data.message);
      } else {
        setPurchaseError('购买资源失败，请稍后再试');
      }
    } finally {
      setPurchaseLoading(false);
    }
  };

  // 渲染购买确认弹窗
  const renderPurchaseModal = () => {
    if (!showPurchaseModal) return null;

    return (
      <div className="purchase-modal-overlay">
        <div className="purchase-modal">
          <div className="purchase-modal-header">
            <h2>{resource.isFree ? '确认获取免费资源' : '确认购买'}</h2>
            <button 
              className="close-modal-btn"
              onClick={() => setShowPurchaseModal(false)}
            >
              ×
            </button>
          </div>
          
          <div className="purchase-modal-content">
            <div className="purchase-info-item">
              <span>资源名称:</span>
              <span>{resource.title}</span>
            </div>
            <div className="purchase-info-item">
              <span>价格:</span>
              <span>{resource.isFree ? '免费 (0 积分)' : `${resource.price} 积分`}</span>
            </div>
            
            {purchaseError && (
              <div className="error-message" style={{ marginTop: '10px' }}>
                {purchaseError}
              </div>
            )}
          </div>
          
          <div className="purchase-modal-actions">
            <button 
              className="cancel-purchase-btn"
              onClick={() => setShowPurchaseModal(false)}
              disabled={purchaseLoading}
            >
              取消
            </button>
            <button 
              className="confirm-purchase-btn"
              onClick={confirmPurchase}
              disabled={purchaseLoading}
            >
              {purchaseLoading ? '处理中...' : (resource.isFree ? '确认获取' : '确认购买')}
            </button>
          </div>
        </div>
      </div>
    );
  };

  // 渲染网络选择组件
  const renderNetworkSelection = () => {
    if (!resource.availableNetworks || resource.availableNetworks.length === 0) {
      return null;
    }

    const selectedNetwork = resource.availableNetworks.find(
      network => network.networkId === selectedNetworkId
    );

    return (
      <div className="available-networks-section">
        <div className="network-selection">
          <label className="network-label">选择可用网络：</label>
          <select 
            className="network-select"
            value={selectedNetworkId || ''}
            onChange={(e) => setSelectedNetworkId(parseInt(e.target.value))}
          >
            {resource.availableNetworks.map(network => (
              <option key={network.networkId} value={network.networkId}>
                {network.name} - {network.isPublic ? '公网' : '局域网'}
                {network.isMember ? ' (已加入)' : ''}
              </option>
            ))}
          </select>
        </div>
        
        {selectedNetwork && (
          <div className="selected-network-info">
            <div className="network-item">
              <div className="network-main-info">
                <span className="network-name">{selectedNetwork.name}</span>
                <div className="network-badges">
                  <span className={`network-type-badge ${selectedNetwork.isPublic ? 'public' : 'private'}`}>
                    {selectedNetwork.isPublic ? '公网' : '局域网'}
                  </span>
                  <span className={`network-status-badge ${selectedNetwork.status}`}>
                    {selectedNetwork.status === 'active' ? '活跃' : '非活跃'}
                  </span>
                </div>
              </div>
              <div className="network-sub-info">
                <span className="network-address">{selectedNetwork.physicalAddress}</span>
                <span className="network-member">{selectedNetwork.isMember ? '成员' : '非成员'}</span>
              </div>
              <div className="network-tracker">
                <span className="tracker-label">Tracker地址:</span>
                <span className="tracker-url">{selectedNetwork.trackerUrl}</span>
              </div>
            </div>
          </div>
        )}
      </div>
    );
  };

  // 渲染资源状态和可用网络
  const renderResourceStatusSection = () => {
    // 如果资源已购买或入库，显示已入库状态和可用网络
    if (resource.isPurchased) {
      return (
        <div className="resource-status-section">
          <div className="library-status-card">
            <div className="status-icon">
              <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <circle cx="12" cy="12" r="10" fill="#4CAF50"/>
                <path d="M8.5 12.5L11 15L15.5 10.5" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
            </div>
            <div className="status-content">
              <span className="status-text">已入库</span>
              {resource.purchaseInfo && (
                <span className="purchase-time">
                  {new Date(resource.purchaseInfo.purchaseTime).toLocaleDateString()}
                </span>
              )}
            </div>
          </div>
          
          {/* 使用新的网络选择组件 */}
          {renderNetworkSelection()}
        </div>
      );
    }
    
    // 如果资源未购买，显示获取按钮
    return (
      <div className="purchase-section">
        <p className="purchase-hint">
          {resource.isFree ? '此资源免费，点击获取后即可查看可用网络' : '此资源需要购买后才能查看可用网络'}
        </p>
        <button 
          className="buy-btn"
          onClick={handlePurchase}
        >
          {resource.isFree ? '免费获取' : `购买 (${resource.price} 积分)`}
        </button>
      </div>
    );
  };

  // 处理评论分页变化
  const handleCommentPaginationChange = (page, pageSize) => {
    setCommentPageNum(page);
    setCommentPageSize(pageSize);
  };

  const renderCommentsSection = () => {
    return (
      <div className="comments-section">
        {/* 评论发布区域 */}
        <div className="comment-form">
          <div className="form-header">
            <h3>💬 发表评论</h3>
            <span className="form-subtitle">分享你的想法和建议</span>
          </div>
          
          <div className="comment-input-container">
            <div className="user-avatar">
              <div className="avatar-placeholder">
                {localStorage.getItem('username')?.charAt(0)?.toUpperCase() || 'U'}
              </div>
            </div>
            
            <div className="comment-input-area">
              <textarea
                value={newComment}
                onChange={(e) => setNewComment(e.target.value)}
                placeholder="写下你的评论..."
                rows={4}
                className="comment-textarea"
                maxLength={1000}
              />
              
              <div className="input-footer">
                <div className="char-count">
                  {newComment.length}/1000
                </div>
                
                <div className="comment-actions">
                  <div className="comment-image-upload">
                    <input
                      id="comment-images"
                      type="file"
                      multiple
                      accept="image/*"
                      onChange={handleCommentImageChange}
                      style={{ display: 'none' }}
                    />
                  </div>
                  
                  <button
                    onClick={handleSubmitComment}
                    disabled={submittingComment || !newComment.trim()}
                    className="submit-comment-btn"
                  >
                    {submittingComment ? (
                      <>
                        <span className="loading-spinner"></span>
                        <span>发布中...</span>
                      </>
                    ) : (
                      <>
                        <span>🚀</span>
                        <span>发表评论</span>
                      </>
                    )}
                  </button>
                </div>
              </div>
              
              {commentImages.length > 0 && (
                <div className="selected-images">
                  <div className="images-preview">
                    {commentImages.map((image, index) => (
                      <div key={index} className="image-preview">
                        <img 
                          src={URL.createObjectURL(image)} 
                          alt={`预览图 ${index + 1}`}
                        />
                        <button 
                          onClick={() => setCommentImages(prev => prev.filter((_, i) => i !== index))}
                          className="remove-image-btn"
                        >
                          ×
                        </button>
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
  
        {/* 评论列表头部 */}
        <div className="comments-header">
          <div className="comments-stats">
            <div className="stats-main">
              <span className="comments-count">{commentTotal}</span>
              <span className="comments-label">条评论</span>
            </div>
          </div>
          
          <div className="comments-controls">
            <div className="sort-container">
              <label className="sort-label">排序方式:</label>
              <select
  value={commentOrderBy}
  onChange={(e) => {
    setCommentOrderBy(e.target.value);
    setCommentPageNum(1);
    // fetchComments 会在 useEffect 中自动触发
  }}
  className="sort-select"
>
                <option value="likeCount">👍 最多点赞</option>
                <option value="updatedTime">🔄 最近更新</option>
              </select>
            </div>
          </div>
        </div>
  
        {/* 评论列表 */}
        <div className="comments-list">
          {commentsLoading ? (
            <div className="comments-loading">
              <div className="loading-spinner"></div>
              <span>加载评论中...</span>
            </div>
          ) : commentsError ? (
            <div className="comments-error">
              <div className="error-icon">⚠️</div>
              <div className="error-text">{commentsError}</div>
              <button onClick={() => fetchComments(true)} className="retry-btn">
                🔄 重试
              </button>
            </div>
          ) : !comments || comments.length === 0 ? (
            <div className="no-comments">
              <div className="no-comments-icon">💬</div>
              <div className="no-comments-text">暂无评论</div>
              <div className="no-comments-subtitle">快来发表第一条评论吧！</div>
            </div>
          ) : (
            <div className="comments-container">
              {comments.map((comment, index) => {
                const currentUserId = currentUser?.userId;
                const isOwnComment = comment.userId === currentUserId;
                
                return (
                  <div 
                    key={comment.commentId} 
                    className={`comment-item ${isOwnComment ? 'own-comment' : ''}`}
                  >
                    {/* 如果是自己的评论，显示置顶标识 */}
                    {isOwnComment && (
                    <div className="top-comment-badge">
                    📌 我的评论(置顶)
                   </div>
                    )}
                    
                    <div className="comment-avatar">
                      <div className="avatar-placeholder">
                        {(comment.username || comment.userName || 'U').charAt(0).toUpperCase()}
                      </div>
                      {/* 显示用户头像（如果有） */}
                      {comment.avatarUrl && (
                        <img 
                          src={comment.avatarUrl} 
                          alt="用户头像"
                          className="user-avatar-img"
                          onError={(e) => {
                            e.target.style.display = 'none';
                          }}
                        />
                      )}
                    </div>
                    
                    <div className="comment-content-wrapper">
                      <div className="comment-header">
                        <div className="comment-user-info">
                          <span className={`user-name ${isOwnComment ? 'own-user' : ''}`}>
                            {comment.username || comment.userName || '匿名用户'}
                            {isOwnComment && <span className="me-badge">我</span>}
                          </span>
                          <span className="comment-time">
                            {new Date(comment.createdAt).toLocaleString()}
                          </span>
                          {comment.updatedAt !== comment.createdAt && (
                            <span className="comment-edited">
                              已编辑
                            </span>
                          )}
                        </div>
                        
                        {isOwnComment && (
                          <div className="comment-actions">
                            <button
                              onClick={() => handleEditComment(comment.commentId, comment.content)}
                              className="edit-comment-btn"
                              title="编辑评论"
                            >
                              ✏️
                            </button>
                            <button
                              onClick={() => handleDeleteComment(comment.commentId)}
                              className="delete-comment-btn"
                              title="删除评论"
                            >
                              🗑️
                            </button>
                          </div>
                        )}
                      </div>
                      
                      <div className="comment-content">
                        {editingCommentId === comment.commentId ? (
                          <div className="comment-edit-form">
                            <textarea
                              value={editingContent}
                              onChange={(e) => setEditingContent(e.target.value)}
                              className="edit-textarea"
                              rows={3}
                              maxLength={1000}
                            />
                            <div className="edit-actions">
                              <button
                                onClick={() => handleSaveEdit(comment.commentId)}
                                className="save-edit-btn"
                              >
                                ✅ 保存
                              </button>
                              <button
                                onClick={handleCancelEdit}
                                className="cancel-edit-btn"
                              >
                                ❌ 取消
                              </button>
                            </div>
                          </div>
                        ) : (
                          <div className="comment-text">{comment.content}</div>
                        )}
                      </div>
                      
                      <div className="comment-footer">
                        <button
                          onClick={() => handleLikeComment(comment.commentId, comment.isLiked)}
                          className={`like-comment-btn ${comment.isLiked ? 'liked' : ''}`}
                          disabled={isOwnComment} // 不能给自己的评论点赞
                          title={isOwnComment ? '不能给自己的评论点赞' : (comment.isLiked ? '取消点赞' : '点赞')}
                        >
                          <span className="like-icon">
                            {comment.isLiked ? '❤️' : '🤍'}
                          </span>
                          <span className="like-count">
                            {comment.likesCount || comment.likeCount || 0}
                          </span>
                        </button>
                        
                        <div className="comment-index">
                          #{index + 1 + (commentPageNum - 1) * commentPageSize}
                        </div>
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>
  
        {/* 分页器 */}
        {commentTotal > commentPageSize && (
          <div className="comments-pagination">
            <PaginationComponent
              current={commentPageNum}
              pageSize={commentPageSize}
              total={commentTotal}
              onChange={handleCommentPaginationChange}
            />
          </div>
        )}
      </div>
    );
  };

  if (loading) {
    return (
      <MainLayout>
        <div className="loading-container">
          <div className="loading-spinner"></div>
          <p>加载中...</p>
        </div>
      </MainLayout>
    );
  }

  if (error) {
    return (
      <MainLayout>
        <div className="error-message">{error}</div>
      </MainLayout>
    );
  }

  if (!resource) {
    return (
      <MainLayout>
        <div className="no-resource">资源未找到</div>
      </MainLayout>
    );
  }

  return (
    <MainLayout>
      <div className="resource-detail-container">
        <div className="breadcrumb">
          <Link to="/categories">资源搜索</Link> / {resource.title}
        </div>
        
        <div className="resource-detail-card">
          <div className="resource-header">
            <div className="resource-cover">
              <img 
                src={resource.coverUrl || '/default-cover.jpg'} 
                alt={resource.title}
                onError={(e) => { e.target.src = '/default-cover.jpg' }}
              />
              {resource.isFree && <span className="free-badge">免费</span>}
            </div>
            
            <div className="resource-header-info">
              <h1 className="resource-title">{resource.title}</h1>
              
              <div className="resource-meta-info">
                <span className="resource-category">
                  分类： {resource.categoryName}
                </span>
                <span className="resource-uploaded-time">
                  上传时间：{new Date(resource.createdAt).toLocaleDateString()}
                </span>
                <span className="resource-uploaded-time">
                  最后更新时间：{new Date(resource.updatedAt).toLocaleDateString()}
                </span>
              </div>
              
              <div className="resource-stats">
                <div className="stat-item">
                <span className="stat-icon">⬇️</span>
                  <span>{resource.torrentDownloadsCount || 0}</span>
                  <label>下载数</label>
                </div>
                <div className="stat-item">
                <span className="stat-icon">👍</span>
                  <span>{resource.likesCount || 0}</span>
                  <label>点赞数</label>
                </div>
                <div className="resource-actions">
                <button 
                  className={`like-btn ${isLiked ? 'active' : ''}`}
                  onClick={handleLike}
                >               
                  {isLiked ? '已点赞' : '点赞'}
                </button>
              </div>
              </div>
              
              <div className="resource-tags">
                <span className="tags-title">标签：</span>
                {resource.tags && resource.tags.map((tag, index) => (
                  <Link 
                    key={index} 
                    to={`/categories?tags=${tag}`}
                    className="tag"
                  >
                    {tag}
                  </Link>
                ))}
              </div>
              
              <div className="resource-actions">
                {/* <button 
                  className={`like-btn ${isLiked ? 'active' : ''}`}
                  onClick={handleLike}
                >               
                  {isLiked ? '已点赞' : '点赞'}
                </button> */}
                
                {renderResourceStatusSection()}
              </div>
            </div>
          </div>
          
          <div className="resource-details">
            <div className="details-tabs">
              <button 
                className={`tab-btn ${activeTab === 'detail' ? 'active' : ''}`}
                onClick={() => setActiveTab('detail')}
              >
                资源详情
              </button>
              <button 
                className={`tab-btn ${activeTab === 'comments' ? 'active' : ''}`}
                onClick={() => setActiveTab('comments')}
              >
                评论 
              </button>
            </div>
            

<div className="details-content">
  {activeTab === 'detail' ? (
    <>
      <div className="resource-description">
        <h3>资源描述</h3>
        <div className="description-content">
          {resource.description || '暂无描述'}
        </div>
      </div>
      
      <div className="resource-info-table">
        <h3>资源信息</h3>
        <table>
          <tbody>
            <tr>
              <td>文件大小</td>
              <td>{resource.fileSize ? `${(resource.fileSize / (1024 * 1024)).toFixed(2)} MB` : '未知'}</td>
            </tr>
            <tr>
              <td>文件格式</td>
              <td>{resource.fileFormat || '未知'}</td>
            </tr>
            <tr>
              <td>资源类型</td>
              <td>{resource.categoryName}</td>
            </tr>
            <tr>
              <td>下载方式</td>
              <td>BT种子</td>
            </tr>
            <tr>
              <td>最后更新</td>
              <td>{resource.updatedAt ? new Date(resource.updatedAt).toLocaleDateString() : '未知'}</td>
            </tr>
          </tbody>
        </table>
      </div>
      
      <div className="resource-preview">
        <h3>资源预览</h3>
        {resource.previewImages && resource.previewImages.length > 0 ? (
          <div className="preview-images">
            {resource.previewImages.map((image, index) => (
              <div className="preview-image" key={index}>
                <img src={image} alt={`预览图 ${index + 1}`} />
              </div>
            ))}
          </div>
        ) : (
          <p className="no-preview">暂无预览图</p>
        )}
      </div>
    </>
  ) : (
    // 评论标签页内容
    renderCommentsSection()
  )}
</div>
          </div>
        </div>
        
        {/* Related resources section */}
        {resource.relatedResources && resource.relatedResources.length > 0 && (
          <div className="related-resources">
            <h2>相关资源推荐</h2>
            <div className="resources-grid">
              {resource.relatedResources.map(related => (
                <div key={related.resourceId} className="resource-card">
                  <div className="resource-image">
                    <img 
                      src={related.coverUrl || '/default-cover.jpg'} 
                      alt={related.title}
                      onError={(e) => { e.target.src = '/default-cover.jpg' }}
                    />
                    {related.isFree && <span className="free-badge">免费</span>}
                  </div>
                  <div className="resource-info">
                    <h3 className="resource-title" title={related.title}>
                      {related.title.length > 20 ? related.title.substring(0, 20) + '...' : related.title}
                    </h3>
                    <div className="resource-meta">
                      <span className="category-label">{related.categoryName}</span>
                      <div className="resource-stats">
                        <span><i className="icon-like"></i> {related.likesCount}</span>
                        <span><i className="icon-download"></i> {related.torrentDownloadsCount}</span>
                      </div>
                    </div>
                  </div>
                  <div className="resource-actions">
                    <Link to={`/resource/detail/${related.resourceId}`} className="btn view-btn">查看详情</Link>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}
      </div>
      
      {/* 购买确认弹窗 */}
      {renderPurchaseModal()}
      
      {/* Toast组件 */}
      {toast.show && (
        <Toast 
          message={toast.message} 
          onClose={closeToast}
        />
      )}
    </MainLayout>
  );
};

export default ResourceDetail;